<template>
	<s-pull-scroll class="s-pull-scroll wrap" :down-offset="120" showDownSuccess="true" ref="pullScroll"
		:pullDown="pullDown">
		<view class="page-main">
			<view class="chat-messages-body">
				<!--      单个消息块  -->
				<view v-for="(conversation, index) in sConversationList" :key="index" style="margin-bottom: 3vw">
					<uni-swipe-action>
						<uni-swipe-action-item :right-options="options2" :show="isOpened[index]" :auto-close="false"
							@change="change($event, index)" @click="bindClick($event, index,conversation)">
							<view class="message-card" @click="goForChat(conversation)">
								<view class="left-part">
									<view class="profile-photo" :style="{
                      backgroundImage:
                        'url(' + profilePhoto(conversation.chatterInfo) + ')',
                    }">
										<view class="message-dot" v-if="conversation.unreadMessageCount > 0">
											{{ conversation.unreadMessageCount }}</view>
									</view>
									<view class="text-wrapper">
										<view class="opposite-name">{{
                      displayChatName(conversation.chatterInfo, conversation)
                    }}</view>
										<view class="opposite-content">{{
                      displayChatContent(conversation.latestMessage)
                    }}</view>
									</view>
								</view>
								<view class="right-part">
									<view class="date">{{
                    rongChatTime(conversation.latestMessage.sentTime)
                  }}</view>
								</view>
							</view>
						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
				<uni-load-more class="loadMore" :status="msgStatus" :icon-size="12" :content-text="msgContentText" />
			</view>
		</view>
	</s-pull-scroll>
</template>

<script>
	import {
		USER_ORIENTED
	} from '../../util/config.js'
	import {
		appMixin
	} from '../../util/reuse';
	import {
		chatMixin
	} from '../../util/reuse/chatMixin';
	import {
		filter
	} from '../../util/reuse/filter';
	import {
		getOppoIdFrom,
		getOppositeIdFrom,
		imService,
		RongIMLib
	} from '../../util/rongCloud/cloudUtil';
	import {
		authRouterGuard,
		didntLoggedIn,
		rongGetChatterProfile,
		uniSetStorageSync
	} from '../../util/funcs';
	import {
		TOAST_DURATION,
		uniNavigate,
		uniShowToast
	} from '../../util/misc';
	import {
		CHATTER_TO
	} from '../../util/rongCloud/messaging';

	export default {
		mixins: [appMixin, chatMixin, filter],
		
		data() {
			return {
				isUSER_ORIENTED: USER_ORIENTED,
				show: false,
				isOpened: [],
				options1: [{
					text: '取消置顶',
				}, ],
				options2: USER_ORIENTED ? [{
						text: '标记已读',
						style: {
							backgroundColor: '#4e4e4e',
						},
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#f65959',
						},
					}, {
						text: '举报',
						style: {
							backgroundColor: 'red',
						},
					},
				] : [{
						text: '标记已读',
						style: {
							backgroundColor: '#4e4e4e',
						},
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#f65959',
						},
					}
				],
				swipeList: [],
			};
		},
		
		onLoad: async function() {
			authRouterGuard(this).then((res) => {
				// console.log('auth passed.');
				this.initPageData();
			});
		},
		
		components: {},
		
		methods: {
			report() {
				uniNavigate('/report/report');
			},
			pullDown(pullScroll) {
				let timeout = this.pullTesting ? 10000 : 200;
				if (didntLoggedIn(false)) {
					pullScroll.success();
					return;
				}
				setTimeout(async () => {
					await this.initPageData();
					pullScroll.success();
					this.msgStatus = 'nomore';
				}, timeout); // 不给延迟, 就怕网速太快了
			},
			async initPageData() {
				return new Promise(async (resolve) => {
					await this.updateGlobalConversation();
					// 因为有时候电脑会刷新, 导致需要更新两遍
					setTimeout(() => {
						if (this.sConversationList.length < 1) {
							this.updateAgain();
						}
					}, TOAST_DURATION);
					resolve();
				});
			},
			async updateAgain() {
				// console.log('update again');
				await this.updateGlobalConversation();
				this.msgStatus = 'nomore';
			},
			clearAllConversation() {
				uniShowToast('别点错了', false);
				console.log('im: ', imService);
				let targetIdArr = [];
				let conversation;
				for (conversation of this.sConversationList) {
					targetIdArr.push(getOppositeIdFrom(conversation));
				}
				let promiseArr = [];
				for (let targetId of targetIdArr) {
					conversation = imService.Conversation.get({
						targetId: targetId,
						type: RongIMLib.CONVERSATION_TYPE.PRIVATE,
					});
					promiseArr.push(conversation.destory());
				}
				Promise.all(promiseArr).then((resArr) => {
					console.log(resArr);
					uniShowToast('重置成功', false);
					this.set_sConversationList([]);
				});
			},
			
			async goForChat(conversation) {
				// console.log(conversation);
				let chatter;
				if (conversation.chatterInfo) {
					console.log('会话的chatter info 拿来用');
					chatter = conversation.chatterInfo
				} else {
					chatter = await rongGetChatterProfile(getOppositeIdFrom(conversation));
				}

				uniSetStorageSync(CHATTER_TO, chatter);
				if (chatter) uniNavigate('/chatting/chatting');
			},

			async markAsRead(i) {
				await this.markConversationAsRead(
					getOppoIdFrom(this.sConversationList[i].latestMessage)
				);
				this.sConversationList[i].unreadMessageCount = 0;
				// 重新计算tabBar badge未读数
				this.updateTabBarBadge();
			},

			change(e, index) {
				this.$set(this.isOpened, index, e);
			},
			
			bindClick(e, i, conversation) {
				let text = e.content.text;
				if (text === '删除') {
					// console.log('删除:', i);
					let targetId = getOppositeIdFrom(this.sConversationList[i]);
					this.deleteConversationById(targetId, true);
				} else if (text == '举报') {
					console.log(conversation)
					uniNavigate(`/report/report?id=${conversation.targetId}&name=${conversation.chatterInfo.name}`);
				} else {
					this.markAsRead(i);
				}
			},
		},
	
		updated: function() {},
	};
</script>

<style lang="scss" scoped>
	@import '../../assets/styles/global';

	.inform {
		height: 88rpx;
		text-align: center;
		line-height: 88rpx;
		font-weight: bold;
		position: fixed;
		top: 0;
		width: 100%;
		font-size: 32rpx;
		background-color: #FFFFFF;
		z-index: 998;
	}

	.report {
		position: absolute;
		font-size: 24rpx;
		width: 80rpx;
		height: 40rpx;
		line-height: 40rpx;
		top: 24rpx;
		right: 20rpx;
		background-color: #004FBF;
		color: #FFFFFF;
		border-radius: 8rpx;
	}

	.clear-all-conversation {
		width: 10vw;
		height: 10vw;
		background-color: #004fbf;
		color: white;
		top: 50vw;
		left: 0;
		position: fixed;
		z-index: 10;
	}

	.page-main {
		background-color: $greyBackgroundColor;
		min-height: 100vh;
		// #ifdef APP-PLUS || MP-WEIXIN
		min-height: 100vh;

		// #endif
		.chat-messages-body {
			overflow: scroll;
			flex: 1;
			display: flex;
			flex-direction: column;
			padding: 28rpx 32rpx;
			justify-content: flex-start;
			align-items: flex-start;

			.loadMore {
				margin: 0 auto;
			}

			.message-card {
				overflow: hidden;
				margin: 0 auto 0vw auto;
				width: 91vw;
				height: 126rpx;
				background-color: #ffffff;
				border-radius: 8rpx;
				@include center;
				justify-content: space-between;
				padding-left: 28rpx;
				padding-right: 28rpx;

				.left-part {
					display: flex;

					.profile-photo {
						border: 2rpx solid grey;
						width: 72rpx;
						height: 72rpx;
						background-color: #888888;
						border-radius: 50%;
						@include cover-no-repeat-center;
						margin-right: 46rpx;
						position: relative;

						.message-dot {
							position: absolute;
							top: 0;
							right: 0;
							width: 4vw;
							height: 4vw;
							font-size: 10px;
							color: white;
							@include center;
							background-color: #ff271d;
							border-radius: 50%;
						}
					}

					.text-wrapper {
						max-width: 330rpx;

						.opposite-name {
							max-width: 200rpx;
							@include ellipsis;
							height: 40rpx;
							font-size: 28rpx;
							color: #232323;
						}

						.opposite-content {
							width: 350rpx;
							@include ellipsis;
							display: flex;
							align-items: center;
							height: 34rpx;
							font-size: 24rpx;
							color: #969799;
						}
					}
				}

				.right-part {
					display: flex;
					justify-content: flex-start;
					align-items: flex-start;
					height: 100%;

					.date {
						max-width: 180rpx;
						position: relative;
						top: 26rpx;
						/*background-color: yellow;*/
						height: 34rpx;
						font-size: 24rpx;
						color: #323233;
					}
				}
			}

			.swipe-delete {
				width: 91vw;
				height: 126rpx;

				/*overflow: hidden;*/
			}
		}
	}
</style>
